package com.shunda.trade.service.impl;

import com.shunda.common.core.domain.entity.SysDept;
import com.shunda.system.mapper.SysDeptMapper;
import com.shunda.system.service.ISysConfigService;
import com.shunda.trade.constant.TradeConstants;
import com.shunda.trade.entity.*;
import com.shunda.trade.mapper.CustomerStationsRecordMapper;
import com.shunda.trade.mapper.TradeOrderProfitMapper;
import com.shunda.trade.mapper.TradeUserProfitMapper;
import com.shunda.trade.mapper.TradeOrderMapper;
import com.shunda.trade.service.TradeOrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 用户信息表(TradeOrder)表服务实现类
 *
 * @author makejava
 * @since 2025-03-13 21:36:41
 */
@Service("tradeOrderService")
public class TradeOrderServiceImpl implements TradeOrderService {
    @Resource
    private TradeOrderMapper tradeOrderDao;

    @Resource
    private TradeOrderProfitMapper tradeOrderProfitDao;
    @Resource
    private TradeUserProfitMapper tradeUserProfitDao;

    @Resource
    private CustomerStationsRecordMapper customerStationsRecordDao;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private SysDeptMapper sysDeptMapper;
    /**
     * 通过ID查询单条数据
     *
     * @param orderId 主键
     * @return 实例对象
     */
    @Override
    public TradeOrder queryById(Long orderId) {
        return this.tradeOrderDao.queryById(orderId);
    }

    /**
     * 分页查询
     *
     * @param tradeOrder 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<TradeOrder> queryByPage(TradeOrder tradeOrder, PageRequest pageRequest) {
        long total = this.tradeOrderDao.count(tradeOrder);
        return new PageImpl<>(this.tradeOrderDao.queryAllByLimit(tradeOrder, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param tradeOrder 实例对象
     * @return 实例对象
     */
    @Override
    public TradeOrder insert(TradeOrder tradeOrder) {
        this.tradeOrderDao.insert(tradeOrder);
        return tradeOrder;
    }

    /**
     * 修改数据
     *
     * @param tradeOrder 实例对象
     * @return 实例对象
     */
    @Override
    public TradeOrder update(TradeOrder tradeOrder) {
        this.tradeOrderDao.update(tradeOrder);
        return this.queryById(tradeOrder.getOrderId());
    }

    /**
     * 通过主键删除数据
     *
     * @param orderId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long orderId) {
        return this.tradeOrderDao.deleteById(orderId) > 0;
    }


    /**
     * 根据id查支付成功的订单
     * @param orderId
     * @return
     */
    public TradeOrder selectSuccessByOrderId(Long orderId) {
        return tradeOrderDao.selectSuccessByOrderId(orderId);
    }

    /**
     * 订单支付，支付成功后进行后续逻辑
     * @param orderId
     */
    @Override
    @Transactional
    public void paymentSuccessful(Long orderId) {
        //根据id查支付成功的订单
        TradeOrder tradeOrder = this.selectSuccessByOrderId(orderId);
        if(ObjectUtils.isEmpty(tradeOrder)) {
            return;
        }
        //加油站id
        Long deptId = tradeOrder.getDeptId();
        //业务员id
        Long salesmanId = tradeOrder.getSalesmanId();
        //用户id
        Long userId = tradeOrder.getUserId();
        //金额（默认单位元）
        BigDecimal oilAmount = BigDecimal.valueOf(tradeOrder.getOilAmount());
        //总分润金额
        BigDecimal profitAmount = BigDecimal.valueOf(tradeOrder.getProfitAmount());
        //订单时间
        Date orderDate = tradeOrder.getOrderDate();
        //支付方式（1线上支付2线下支付）
        String payMethod = tradeOrder.getPayMethod();
        //如果是线下支付，从这个加油站的可体现金额里 扣除分润金额
        if(StringUtils.equals("2",payMethod)) {
            SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
            BigDecimal profit = sysDept.getProfit();
            //加油站金额更新实体
            SysDept sysDeptUpdate = new SysDept();
            sysDeptUpdate.setDeptId(deptId);
            sysDeptUpdate.setProfit(profit.subtract(profitAmount));
            sysDeptMapper.updateDept(sysDeptUpdate);
        }
        //用户分润比例
        BigDecimal userProportion = new BigDecimal(configService.selectConfigByKey("userProportion"));
        //加油站分润比例
        BigDecimal deptProportion = new BigDecimal(configService.selectConfigByKey("deptProportion"));
        //平台分润比例
        BigDecimal platformProportion = new BigDecimal(configService.selectConfigByKey("platformProportion"));
        //非用户的分润总金额（元）（35%）
        BigDecimal noUserProfitAmount = profitAmount.multiply(deptProportion.add(platformProportion));

        BigDecimal userProfitAmount = profitAmount.multiply(userProportion);
        //加油站分润金额
        BigDecimal deptProfitAmount = profitAmount.multiply(deptProportion);
        //平台分润金额（元）
        BigDecimal platformProfitAmount = profitAmount.multiply(platformProportion);


        //  拼装订单分润表参数
        TradeOrderProfit tradeOrderProfit = new TradeOrderProfit();
        tradeOrderProfit.setOrderId(orderId);
        tradeOrderProfit.setDeptId(deptId);
        //  TODO 先不做三方加油站
        tradeOrderProfit.setThreeDeptId(null);
        tradeOrderProfit.setSalesmanId(salesmanId);
        tradeOrderProfit.setProfitAmount(noUserProfitAmount.doubleValue());
        tradeOrderProfit.setDeptProfitAmount(deptProfitAmount.doubleValue());
        //  TODO 先不做三方加油站
        tradeOrderProfit.setThreeDeptProfitAmount(null);
        tradeOrderProfit.setPlatformProfitAmount(platformProfitAmount.doubleValue());
        tradeOrderProfit.setOrderDate(orderDate);
        // 插入 订单分润表
        tradeOrderProfitDao.insert(tradeOrderProfit);



        // 拼装收入流水表参数
        TradeProfitFlow tradeProfitFlow = new TradeProfitFlow();
        tradeProfitFlow.setOrderId(orderId);
        tradeProfitFlow.setOrderId(orderId);
        tradeProfitFlow.setProfitAmount(profitAmount.doubleValue());
        tradeProfitFlow.setOrderProfitAmount(noUserProfitAmount.doubleValue());
        tradeProfitFlow.setDate(orderDate);
        // TODO  非用户分润id 是不是  trade_order_profit表的 profitId
        tradeProfitFlow.setOrderProfitId(tradeOrderProfit.getProfitId());
        tradeProfitFlow.setUserProfitAmount(userProfitAmount.doubleValue());
        //交易类型（1-收入，2结余）
        tradeProfitFlow.setType(TradeConstants.INCOME);
        tradeProfitFlow.setDescription(null);

        //拼装用户分润表参数
        TradeUserProfit tradeUserProfit = new TradeUserProfit();
        tradeUserProfit.setUserId(userId);
        //当前分润比例（1：金牌0.45，2：银牌0.15，3：铜牌0.05）  新增都是金牌
        tradeUserProfit.setUserProfitPoint(TradeConstants.GOLD);
        //分润股数（100/股）
        BigDecimal userProfitWeight = oilAmount.divide(BigDecimal.valueOf(100.00)).setScale(0, BigDecimal.ROUND_DOWN);
        tradeUserProfit.setUserProfitWeight(userProfitWeight.intValue());
        //用户分润总金额（元）(股数*100后暂停累计)
        tradeUserProfit.setUserProfitAmount(userProfitWeight.multiply(new BigDecimal(100)).doubleValue());
        //分润标记（0累计中，1暂停累计）
        tradeUserProfit.setProfitFlag("0");
        tradeUserProfit.setCreateTime(orderDate);
        tradeUserProfit.setUpdateTime(new Date());
        tradeUserProfitDao.insert(tradeUserProfit);

        // 查询CustomerStationsRecord这个表   如果已有记录  把使用次数加1，如果没有就新增一条 使用次数为1的
        List<CustomerStationsRecord> customerStationsRecords = customerStationsRecordDao.queryByUserIdDeptId(orderId, deptId);
        if (CollectionUtils.isNotEmpty(customerStationsRecords) && customerStationsRecords.size() > 0) {
            CustomerStationsRecord customerStationsRecord = customerStationsRecords.get(1);
            Integer count = customerStationsRecord.getCount();
            count = count + 1;
            CustomerStationsRecord updateRecord = new CustomerStationsRecord();
            updateRecord.setUserId(userId);
            updateRecord.setDeptId(deptId);
            updateRecord.setCount(count);
            updateRecord.setUpdateTime(new Date());
            customerStationsRecordDao.updateByUserIdDeptId(updateRecord);
        }else {
            CustomerStationsRecord customerStationsRecord = new CustomerStationsRecord();
            customerStationsRecord.setUserId(userId);
            customerStationsRecord.setDeptId(deptId);
            customerStationsRecord.setCount(1);
            customerStationsRecord.setCreateTime(new Date());
            customerStationsRecordDao.insert(customerStationsRecord);
        }
    }

    @Override
    public List<TradeOrder> selectOrderPage(TradeOrder tradeOrder) {
        return tradeOrderDao.selectOrderPage(tradeOrder);
    }
}
